<?php
declare (strict_types=1);

namespace app\listener;

use app\common\model\LawCase;
use app\common\model\Trade;

class LawCaseNumUpdated
{
    /**
     * 案源剩余数量 事件监听处理
     *
     * @return mixed
     */
    public function handle(LawCase $lawCase)
    {
        // 计算案源剩余数量

        // 案源已售出数量
        $count = Trade::where('lawCaseId', $lawCase->id)
            ->where('tradeType', TRADE_LAS_CASE)
            ->whereIn('payStatus', [Trade::UNPAID, Trade::PAID])
            ->whereIn('refundStatus', [Trade::NOTREFUND, Trade::REFUNDING, Trade::REFUND_FAILED])
            ->sum('num');
        if (!is_numeric($count)) {
            $count = 0;
        }

        $surplus = $lawCase->num - $count;
        if ($surplus < 0) {
            $surplus = 0;
        }
        $lawCase->surplus = $surplus;
        $lawCase->save();
    }
}
